
import React, { useEffect, useState } from 'react'
import { InfiniteScroll, List, Tag, Tabs } from 'antd-mobile'
import { AuthRoute } from '../web/auth';
import { mineDevice } from '../apis/mineDevice';
import { getToken } from '../tokens';
import { webSend } from '../web/util';
import { formatTime } from '../utils';

export const MineDevicePage: React.FC<{}> = ({ }) => {
    const [data, setData] = useState<any[]>([])
    const [hasMore, setHasMore] = useState(true)
    const [page, setPage] = useState(1)
    const [status, setStatus] = useState(`all`)
    const token = getToken()
    async function initData(status: string) {
        setStatus(status);
        setPage(1)
        const append = await mineDevice({ page: 1, token, status })
        setData(val => append.sort((a, b) => parseInt(a.device_name) - parseInt(b.device_name)))
    }
    async function loadMore() {
        const append = await mineDevice({ page, token, status })
        setData(val => [...val, ...append].sort((a, b) => parseInt(a.device_name) - parseInt(b.device_name)))
        setHasMore(append.length > 0)
        setPage(page + 1)
    }
    const getStatus = (status: string) => {
        switch (status) {
            case '0':
                return `离线`
            case `1`:
                return `在线`
            default:
                return `未知`
        }
    }
    const getStatusColor = (status: string) => {
        switch (status) {
            case '0':
                return `default`
            case `1`:
                return `success`
            default:
                return `danger`
        }
    }
    useEffect(() => {
        webSend('HAS_BACK', true)
    }, [])
    return <AuthRoute>
        <div className='flex flex-col h-full'>
            <Tabs activeKey={status} onChange={e => {
                initData(e);
            }}>
                <Tabs.Tab title='全部' key='all'></Tabs.Tab>
                <Tabs.Tab title='在线' key='online'></Tabs.Tab>
                <Tabs.Tab title='离线' key='offline'></Tabs.Tab>
            </Tabs>
            <List>
                {data.map((item, index) => (
                    <List.Item key={item.id} title={item.device_name} extra={<div className='flex'>
                        {item.status === `1` ? <div className='mr-8px'>{formatTime(item.ping_time)}</div> : null}
                        <div>
                            <Tag color={getStatusColor(item.status)}>{getStatus(item.status)}</Tag>
                        </div>
                    </div>}></List.Item>
                ))}
            </List>
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
        </div>
    </AuthRoute>
}
